package orm

import (
	"fmt"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/config"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var designDb *gorm.DB

// GormPgSql 初始化 Postgresql 数据库
func GormPgSql(PgSqlUserName, Password, Address string, Port string, DbName string) *gorm.DB {

	log.Info(DbName + " pgsql  链接中。。。")
	var err error
	dsn := "host=" + Address + " user=" + PgSqlUserName + " password=" + Password + " dbname=" + DbName + " port=" + Port + " " + "sslmode=disable TimeZone=Asia/Shanghai"

	pgsqlConfig := postgres.Config{
		DSN:                  dsn, // DSN data source name
		PreferSimpleProtocol: false,
	}

	db, err := gorm.Open(postgres.New(pgsqlConfig), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `user`

		},
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		log.Fatalf("failed to connect database：%v", err)
		return db
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(10)                   // 设置最大空闲连接数
		sqlDB.SetMaxOpenConns(100)                  // 设置最大打开连接数
		sqlDB.SetConnMaxLifetime(time.Second * 550) // 设置连接最大生命周期

		fmt.Println("====gorm====: gorm link PostgreSQL success")

		return db
	}
}

func InitDesignDB() *gorm.DB {
	//designDb = ConnectMySql(config.C.Mysql.UserName, config.C.Mysql.Password, config.C.Mysql.Address, config.C.Mysql.Port, "design_app")
	designDb = GormPgSql(config.C.Pgsql.UserName, config.C.Pgsql.Password, config.C.Pgsql.Address, config.C.Pgsql.Port, config.C.Pgsql.DbName)
	return designDb
}

func GetDesignDB() *gorm.DB {
	return designDb
}
